package gbench.appdemo.mall.mvc.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import gbench.appdemo.mall.mvc.annotation.IRecordParam;
import gbench.common.tree.LittleTree.IRecord;
import static gbench.common.tree.LittleTree.IRecord.*;

/**
 * 提取IRecord中的所有参数
 * @author gbench
 *
 */
@Component
public class IRecordParamResolver implements HandlerMethodArgumentResolver{

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(IRecordParam.class) && 
            IRecord.class.isAssignableFrom(parameter.getParameterType());
    }
    
    /**
     * 把所有的参数都
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        
        final var rec = REC();
        final var name = parameter.getParameterName();// 获取参数名称
        final var annotation = parameter.getParameterAnnotation(IRecordParam.class); // 参数注释
        final var key = annotation==null
            ? name // 默认的参数名称
            : annotation.name(); // 提取参数注解的名字
        if(key==null || "-".equals(key)){// key 是不可能为null ,谢在这里提示一下而已
            final var params = webRequest.getParameterMap();
            params.forEach((k,v)->rec.add(k,v!=null && v.length==1?v[0]:v));
        } else {
            rec.add(key,webRequest.getParameter(key));
        }// if
        return rec;
    }

}
